package com.thread;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PrintOutABC {
    public static void main(String[] args) {
        PrintOut p = new PrintOut(10);
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3,3,2, TimeUnit.SECONDS,new LinkedBlockingQueue<>());
        threadPoolExecutor.submit(() ->{
            p.printOutA();
        });
        threadPoolExecutor.submit(() ->{
           p.printOutB();
        });
        threadPoolExecutor.submit(() ->{
           p.printOutC();
        });
        threadPoolExecutor.shutdown();
    }
}

class PrintOut{

    Lock lock = new ReentrantLock();
    Condition printA = lock.newCondition();
    Condition printB = lock.newCondition();
    Condition printC = lock.newCondition();

    int  k = 0;
    int count;
    public PrintOut(int count){
        this.count = count;
    }

    public void printOutA(){
        for (int i = 1; i <= count ; i++) {
            lock.lock();
            try {
                while (k != 0){
                    printA.await();
                }
                System.out.println(i + ":" + "A");
                k++;
                printB.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    public void printOutB(){
        for (int i = 1; i <= count ; i++) {
            lock.lock();
            try {
                while (k != 1){
                    printB.await();
                }
                System.out.println(i + ":" + "B");
                k++;
                printC.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    public void printOutC(){
        for (int i = 1; i <= count ; i++) {
            lock.lock();
            try {
                while (k != 2){
                    printC.await();
                }
                System.out.println(i + ":" + "C");
                k = 0;
                printA.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

}
